// CLI流式事件处理器
import { StreamEventHandlers } from '../core/stream-events';
import { ToolCall } from '../types';

export class CLIStreamHandler implements StreamEventHandlers {
  private lastWasReasoning = false;
  private debugMode = false;

  constructor(options: { debugMode?: boolean } = {}) {
    this.debugMode = options.debugMode || false;
  }

  onStreamStart = (round: number) => {
    if (round === 1) {
      console.log('\n=== 🤖 AI 开始回答 ===\n');
    } else {
      console.log(`\n=== 🤖 AI 基于工具结果继续回答 (第${round}轮) ===\n`);
    }
  };

  onContent = (content: string) => {
    if (this.lastWasReasoning) {
      process.stdout.write(']\n');
      this.lastWasReasoning = false;
    }
    process.stdout.write(content);
  };

  onReasoning = (reasoning: string) => {
    if (!this.lastWasReasoning) {
      process.stdout.write('\n[🤔 思考: ');
      this.lastWasReasoning = true;
    }
    process.stdout.write(reasoning);
  };

  onReasoningEnd = () => {
    if (this.lastWasReasoning) {
      process.stdout.write(']\n');
      this.lastWasReasoning = false;
    }
  };

  onStreamComplete = () => {
    console.log('\n\n=== ✅ AI 输出完成 ===\n');
  };

  onToolCallsDetected = (toolCalls: ToolCall[]) => {
    console.log(`\n=== 🔧 检测到 ${toolCalls.length} 个工具调用 ===\n`);
    
    toolCalls.forEach((call, index) => {
      console.log(`🛠️  工具 ${index + 1}: ${call.function.name}`);
 
    });
    console.log('');
  };

  onToolExecutionStart = (toolName: string, args: any) => {
    console.log(`🔧 正在执行工具: ${toolName}`);
    if (this.debugMode) {
      console.log(`📝 参数详情:`, JSON.stringify(args, null, 2));
    }
  };

  onToolExecutionComplete = (toolName: string, result: string) => {
    console.log(`✅ 工具 ${toolName} 执行完成`);
    
    const preview = result.length > 100 ? 
      `${result.substring(0, 100)}...` : 
      result;
    
    console.log(`📊 结果: ${preview}`);
    console.log('');
  };

  onToolExecutionError = (toolName: string, error: string) => {
    console.log(`❌ 工具 ${toolName} 执行失败: ${error}`);
    console.log('');
  };

  onConversationComplete = () => {
    console.log('\n=== 🎉 对话完成 ===\n');
  };

  onError = (error: Error) => {
    console.error(`\n❌ 错误: ${error.message}`);
    if (this.debugMode) {
      console.error('错误详情:', error);
    }
    console.log('');
  };

  onDebug = (message: string, data?: any) => {
    if (this.debugMode) {
      console.log(`🐛 调试: ${message}`);
      if (data) {
        console.log('    数据:', data);
      }
    }
  };

  // 设置调试模式
  setDebugMode(enabled: boolean) {
    this.debugMode = enabled;
  }

  getDebugMode(): boolean {
    return this.debugMode;
  }
}
